﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace SampleWinForm
{
  public partial class CrossThread : Form
  {
    Thread m_Thread = null;
    public delegate void InvokeDelegate(int _Param);

    public CrossThread()
    {
      InitializeComponent();
    }

    #region Event Handler
    private void CrossThread_Load(object sender, EventArgs e)
    {
      if (m_Thread == null)
      {
        m_Thread = new Thread(ThreadMethod);
      }
    }

    private void btnStartThread_Click(object sender, EventArgs e)
    {
      if (!btnPause.Enabled)
      {
        m_Thread.Start();
        btnPause.Enabled = true;
      }
    }
    private void btnPause_Click(object sender, EventArgs e)
    {
      if (m_Thread.ThreadState == ThreadState.Suspended)
      {
        m_Thread.Resume();
        btnPause.Text = "Pause";
      }
      else
      {
        m_Thread.Suspend();
        btnPause.Text = "Resume";
      }
    }

    private void CrossThread_FormClosing(object sender, FormClosingEventArgs e)
    {
      //Attention a toujours bien tué un thread une fois celui ci devenu inutile
      if (m_Thread != null)
      {
        m_Thread.Abort();
        m_Thread = null;
      }
    }
    #endregion

    #region Thread Method
    public void ThreadMethod()
    {
      int i = 0;
      while (true)
      {
        BeginInvoke(new InvokeDelegate(InvokeMethod),i);//Invoke : Synchrone / BeginInvoke : Asynchrone
        i++;
        Thread.Sleep(1000);//Obligatoire pour cadencer le thread et surtout permettre au thread principale de rafraichir l'interface graphique
      }
    }

    public void InvokeMethod(int _Param)
    {
      lblModify.Text = "Timer modify by thread : " + _Param.ToString();
    }
    #endregion
  }
}
